package com.thread.demo11;

import java.util.concurrent.atomic.AtomicReference;

public class ThreadJoin {



    public static void test1(){
        System.out.println("11");
        Thread t = Thread.currentThread();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                if(i==5){
                    try {
                        //当前线程等待t线程执行结束之后，join才会返回，才会开始执行当前线程join之后的方法
                        t.join();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("sub="+i);
            }
        }).start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("12");
    }

    public static void test2() throws InterruptedException {
//        AtomicBoolean flag = new AtomicBoolean(false);
        AtomicReference<String> flag = new AtomicReference<>("false");
        Thread t = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                if(i==5){
                    try {
                        //当前线程等待t线程执行结束之后，join才会返回，才会开始执行当前线程join之后的方法
                        Thread.sleep(11);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                flag.set("true");
                System.out.println("sub="+i);
            }
        });
        Thread t2 = new Thread(()->{
            flag.set("true");
            for (int i = 0; i < 10; i++) {
                if(i==5){
                    try {
                        //当前线程等待t线程执行结束之后，join才会返回，才会开始执行当前线程join之后的方法
                        t.join();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("sub2="+i);
            }
        });
        t.start();
        t2.start();

//        t.join();
//        t2.join();
        System.out.println("123="+flag.toString());

        Thread.sleep(100);
        System.out.println("124="+flag.toString());
    }

    public static void main(String[] args) throws InterruptedException {
//        test1();
        test2();
    }
}
